import {Button, Input, ScrollView, Text, View} from '@tarojs/components'
import Taro, {useDidShow, useRouter} from '@tarojs/taro'
import type React from 'react'
import {useCallback, useEffect, useState} from 'react'
import {
  type Contact,
  createOrder,
  type Exhibition,
  getContacts,
  getExhibition,
  getTicketTypes,
  type TicketInfo,
  type TicketType
} from '@/api'
import {getUserInfo, isLoggedIn} from '@/utils/auth'

interface TicketSelection {
  ticketTypeId: number
  ticketTypeName: string
  price: number
  quantity: number
}

const Booking: React.FC = () => {
  const router = useRouter()
  const exhibitionId = Number(router.params.exhibitionId)

  const [exhibition, setExhibition] = useState<Exhibition | null>(null)
  const [ticketTypes, setTicketTypes] = useState<TicketType[]>([])
  const [selections, setSelections] = useState<Map<number, TicketSelection>>(new Map())
  const [buyerName, setBuyerName] = useState('')
  const [buyerPhone, setBuyerPhone] = useState('')
  const [buyerIdCard, setBuyerIdCard] = useState('')
  const [ticketInfos, setTicketInfos] = useState<TicketInfo[]>([])
  const [loading, setLoading] = useState(true)
  const [submitting, setSubmitting] = useState(false)
  const [contacts, setContacts] = useState<Contact[]>([])
  const [showContactSelector, setShowContactSelector] = useState(false)
  const [selectingForVisitor, setSelectingForVisitor] = useState<number | null>(null) // null表示为购票人选择，数字表示为第几张票选择

  // 加载用户手机号
  useEffect(() => {
    const userInfo = getUserInfo()
    if (userInfo?.phone) {
      setBuyerPhone(userInfo.phone)
    }
  }, [])

  const loadData = useCallback(async () => {
    if (!exhibitionId) return

    // 检查登录状态
    if (!isLoggedIn()) {
      Taro.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        Taro.navigateTo({url: '/pages/login/index'})
      }, 1500)
      return
    }

    setLoading(true)
    try {
      const [exhibitionResult, ticketTypesResult, contactsResult] = await Promise.all([
        getExhibition(exhibitionId),
        getTicketTypes(exhibitionId),
        getContacts()
      ])

      if (exhibitionResult.success && exhibitionResult.data) {
        setExhibition(exhibitionResult.data)
      }

      if (ticketTypesResult.success && ticketTypesResult.data) {
        setTicketTypes(ticketTypesResult.data)
      }

      if (contactsResult.success && contactsResult.data) {
        const contactsList = Array.isArray(contactsResult.data) ? contactsResult.data : []
        setContacts(contactsList)

        // 如果有默认联系人，自动填充
        const defaultContact = contactsList.find((c) => c.is_default)
        if (defaultContact) {
          setBuyerName(defaultContact.name)
          setBuyerIdCard(defaultContact.id_card)
        }
      }
    } catch (error) {
      console.error('加载数据失败:', error)
      Taro.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      setLoading(false)
    }
  }, [exhibitionId])

  useDidShow(() => {
    loadData()
  })

  // 更新票数选择
  const updateQuantity = (ticketTypeId: number, ticketTypeName: string, price: number, delta: number) => {
    const newSelections = new Map(selections)
    const current = newSelections.get(ticketTypeId)

    if (current) {
      const newQuantity = Math.max(0, current.quantity + delta)
      if (newQuantity === 0) {
        newSelections.delete(ticketTypeId)
      } else {
        newSelections.set(ticketTypeId, {...current, quantity: newQuantity})
      }
    } else if (delta > 0) {
      newSelections.set(ticketTypeId, {
        ticketTypeId,
        ticketTypeName,
        price,
        quantity: 1
      })
    }

    setSelections(newSelections)

    // 更新票据信息数组
    const totalTickets = Array.from(newSelections.values()).reduce((sum, sel) => sum + sel.quantity, 0)
    const newTicketInfos: TicketInfo[] = []
    for (let i = 0; i < totalTickets; i++) {
      newTicketInfos.push(ticketInfos[i] || {visitor_name: '', visitor_phone: '', visitor_id_card: ''})
    }
    setTicketInfos(newTicketInfos)
  }

  // 更新票据信息
  const updateTicketInfo = (index: number, field: keyof TicketInfo, value: string) => {
    const newTicketInfos = [...ticketInfos]
    newTicketInfos[index] = {...newTicketInfos[index], [field]: value}
    setTicketInfos(newTicketInfos)
  }

  // 选择联系人
  const handleSelectContact = (contact: Contact) => {
    if (selectingForVisitor !== null) {
      // 为游客信息选择联系人
      const newTicketInfos = [...ticketInfos]
      newTicketInfos[selectingForVisitor] = {
        visitor_name: contact.name,
        visitor_phone: contact.phone,
        visitor_id_card: contact.id_card
      }
      setTicketInfos(newTicketInfos)
    } else {
      // 为购票人选择联系人
      setBuyerName(contact.name)
      setBuyerIdCard(contact.id_card)
    }
    setShowContactSelector(false)
    setSelectingForVisitor(null)
    Taro.showToast({
      title: '已选择联系人',
      icon: 'success',
      duration: 1500
    })
  }

  // 打开联系人选择器（为购票人）
  const openContactSelectorForBuyer = () => {
    setSelectingForVisitor(null)
    setShowContactSelector(true)
  }

  // 打开联系人选择器（为游客）
  const openContactSelectorForVisitor = (index: number) => {
    setSelectingForVisitor(index)
    setShowContactSelector(true)
  }

  // 计算总价
  const getTotalAmount = () => {
    return Array.from(selections.values()).reduce((sum, sel) => sum + sel.price * sel.quantity, 0)
  }

  // 计算总票数
  const getTotalTickets = () => {
    return Array.from(selections.values()).reduce((sum, sel) => sum + sel.quantity, 0)
  }

  // 验证手机号
  const validatePhone = (phone: string) => {
    return /^1[3-9]\d{9}$/.test(phone)
  }

  // 验证身份证号
  const validateIdCard = (idCard: string) => {
    return /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/.test(idCard)
  }

  // 提交订单
  const handleSubmit = async () => {
    // 验证票数
    if (selections.size === 0) {
      Taro.showToast({
        title: '请选择票种',
        icon: 'none'
      })
      return
    }

    // 验证购票人信息
    if (!buyerName || !buyerPhone || !buyerIdCard) {
      Taro.showToast({
        title: '请填写购票人信息',
        icon: 'none'
      })
      return
    }

    if (!validatePhone(buyerPhone)) {
      Taro.showToast({
        title: '购票人手机号格式不正确',
        icon: 'none'
      })
      return
    }

    if (!validateIdCard(buyerIdCard)) {
      Taro.showToast({
        title: '购票人身份证号格式不正确',
        icon: 'none'
      })
      return
    }

    // 验证每张票的信息
    const totalTickets = getTotalTickets()
    if (ticketInfos.length !== totalTickets) {
      Taro.showToast({
        title: '请填写所有票的游客信息',
        icon: 'none'
      })
      return
    }

    for (let i = 0; i < ticketInfos.length; i++) {
      const ticket = ticketInfos[i]
      if (!ticket.visitor_name || !ticket.visitor_phone || !ticket.visitor_id_card) {
        Taro.showToast({
          title: `请填写第${i + 1}张票的完整信息`,
          icon: 'none'
        })
        return
      }

      if (!validatePhone(ticket.visitor_phone)) {
        Taro.showToast({
          title: `第${i + 1}张票的手机号格式不正确`,
          icon: 'none'
        })
        return
      }

      if (!validateIdCard(ticket.visitor_id_card)) {
        Taro.showToast({
          title: `第${i + 1}张票的身份证号格式不正确`,
          icon: 'none'
        })
        return
      }
    }

    setSubmitting(true)
    try {
      const items = Array.from(selections.values()).map((sel) => ({
        ticket_type_id: sel.ticketTypeId,
        quantity: sel.quantity
      }))

      const result = await createOrder({
        exhibition_id: exhibitionId,
        buyer_name: buyerName,
        buyer_phone: buyerPhone,
        buyer_id_card: buyerIdCard,
        items,
        tickets: ticketInfos
      })

      if (result.success) {
        Taro.showToast({
          title: '订单创建成功',
          icon: 'success'
        })
        setTimeout(() => {
          Taro.navigateTo({
            url: `/pages/order-detail/index?orderNo=${result.data.order_no}`
          })
        }, 1500)
      } else {
        Taro.showToast({
          title: result.error || '创建订单失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('创建订单失败:', error)
      Taro.showToast({
        title: '创建订单失败',
        icon: 'none'
      })
    } finally {
      setSubmitting(false)
    }
  }

  // 获取票种名称（用于显示票据信息标题）
  const getTicketTypeName = (index: number): string => {
    let count = 0
    for (const sel of Array.from(selections.values())) {
      if (index < count + sel.quantity) {
        return `${sel.ticketTypeName} 第${index - count + 1}张`
      }
      count += sel.quantity
    }
    return `第${index + 1}张票`
  }

  if (loading) {
    return (
      <View className="min-h-screen flex items-center justify-center bg-gradient-to-b from-blue-50 to-blue-100">
        <Text className="text-gray-500">加载中...</Text>
      </View>
    )
  }

  if (!exhibition) {
    return (
      <View className="min-h-screen flex items-center justify-center bg-gradient-to-b from-blue-50 to-blue-100">
        <Text className="text-gray-500">展览不存在</Text>
      </View>
    )
  }

  return (
    <View style={{background: 'linear-gradient(to bottom, #eff6ff, #dbeafe)', minHeight: '100vh'}}>
      <ScrollView scrollY style={{background: 'transparent'}} className="box-border h-screen">
        <View className="p-4 pb-32">
          {/* 展览信息 */}
          <View className="bg-white rounded-2xl shadow-sm p-4 mb-4">
            <Text className="text-lg font-bold text-gray-900 block mb-2">{exhibition.title}</Text>
            <View className="space-y-1">
              <View>
                <Text className="text-sm text-gray-600">地点：{exhibition.location}</Text>
              </View>
              <View>
                <Text className="text-sm text-gray-600">
                  时间：{exhibition.start_date} 至 {exhibition.end_date}
                </Text>
              </View>
            </View>
          </View>

          {/* 票种选择 */}
          <View className="bg-white rounded-2xl shadow-sm p-4 mb-4">
            <Text className="text-base font-bold text-gray-900 block mb-4">选择票种</Text>
            <View className="space-y-3">
              {ticketTypes.map((ticketType) => {
                const selection = selections.get(ticketType.id)
                const quantity = selection?.quantity || 0
                const isSoldOut = ticketType.is_sold_out || false
                const available = ticketType.available || 0

                return (
                  <View
                    key={ticketType.id}
                    className={`flex items-center justify-between py-3 border-b border-gray-100 last:border-0 ${isSoldOut ? 'opacity-50' : ''}`}>
                    <View className="flex-1">
                      <View className="flex items-center gap-2 mb-1">
                        <Text className="text-sm font-medium text-gray-900">{ticketType.name}</Text>
                        {isSoldOut && (
                          <View className="px-2 py-0.5 bg-red-100 rounded">
                            <Text className="text-xs text-red-600 font-medium">售罄</Text>
                          </View>
                        )}
                      </View>
                      <Text className="text-lg font-bold text-blue-600 block">¥{ticketType.price}</Text>
                      {!isSoldOut && available !== -1 && (
                        <Text className="text-xs text-gray-500 block mt-1">剩余 {available} 张</Text>
                      )}
                      {!isSoldOut && available === -1 && (
                        <Text className="text-xs text-gray-500 block mt-1">库存充足</Text>
                      )}
                    </View>
                    <View className="flex items-center gap-2">
                      <View
                        className="w-8 h-8 flex items-center justify-center rounded-full"
                        style={{
                          backgroundColor: quantity === 0 || isSoldOut ? '#f3f4f6' : '#e5e7eb',
                          color: quantity === 0 || isSoldOut ? '#d1d5db' : '#374151',
                          border: 'none',
                          boxShadow: quantity === 0 || isSoldOut ? 'none' : '0 2px 4px rgba(0,0,0,0.1)'
                        }}
                        onClick={() => updateQuantity(ticketType.id, ticketType.name, ticketType.price, -1)}
                        hidden={quantity === 0 || isSoldOut}>
                        <View className="i-mdi-minus text-xl"></View>
                      </View>
                      <View className="min-w-12 px-3 py-2 bg-gray-50 rounded-lg">
                        <Text className="text-lg font-bold text-gray-900 text-center block">{quantity}</Text>
                      </View>
                      <View
                        className="w-8 h-8 flex items-center justify-center rounded-full"
                        style={{
                          backgroundColor:
                            isSoldOut || (available !== -1 && quantity >= available) ? '#f3f4f6' : '#2563eb',
                          color: isSoldOut || (available !== -1 && quantity >= available) ? '#d1d5db' : '#ffffff',
                          border: 'none',
                          boxShadow:
                            isSoldOut || (available !== -1 && quantity >= available)
                              ? 'none'
                              : '0 2px 8px rgba(37,99,235,0.3)'
                        }}
                        onClick={() => updateQuantity(ticketType.id, ticketType.name, ticketType.price, 1)}
                        hidden={isSoldOut || (available !== -1 && quantity >= available)}>
                        <View className="i-mdi-plus text-xl"></View>
                      </View>
                    </View>
                  </View>
                )
              })}
            </View>
          </View>

          {/* 购票人信息 */}
          <View className="bg-white rounded-2xl shadow-sm p-4 mb-4">
            <View className="flex items-center justify-between mb-4">
              <Text className="text-base font-bold text-gray-900">购票人信息</Text>
              {contacts.length > 0 && (
                <Button
                  size="mini"
                  className="bg-blue-50 text-blue-600 rounded-lg text-xs px-3"
                  style={{backgroundColor: '#eff6ff', color: '#2563eb'}}
                  onClick={openContactSelectorForBuyer}>
                  <View className="flex items-center gap-1">
                    <View className="i-mdi-account-multiple text-sm"></View>
                    <Text className="text-blue-600">选择联系人</Text>
                  </View>
                </Button>
              )}
            </View>
            <View className="space-y-3">
              <View>
                <Text className="text-sm text-gray-700 block mb-2">姓名</Text>
                <Input
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
                  placeholder="请输入姓名"
                  value={buyerName}
                  onInput={(e) => setBuyerName(e.detail.value)}
                />
              </View>
              <View>
                <View className="flex items-center justify-between mb-2">
                  <Text className="text-sm text-gray-700">手机号</Text>
                  <Text className="text-xs text-gray-500">（登录账号）</Text>
                </View>
                <Input
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm bg-gray-50"
                  placeholder="请输入手机号"
                  type="number"
                  maxlength={11}
                  value={buyerPhone}
                  disabled
                  style={{backgroundColor: '#f9fafb', color: '#6b7280'}}
                />
              </View>
              <View>
                <Text className="text-sm text-gray-700 block mb-2">身份证号</Text>
                <Input
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
                  placeholder="请输入身份证号"
                  maxlength={18}
                  value={buyerIdCard}
                  onInput={(e) => setBuyerIdCard(e.detail.value.toUpperCase())}
                />
              </View>
              {contacts.length === 0 && (
                <View className="flex items-center gap-2 p-3 bg-blue-50 rounded-lg mt-2">
                  <View className="i-mdi-information text-blue-600 text-lg"></View>
                  <Text className="text-xs text-blue-600 flex-1">您还没有常用联系人，可以在个人中心添加</Text>
                </View>
              )}
            </View>
          </View>

          {/* 游客信息（每张票） */}
          {ticketInfos.length > 0 && (
            <View className="bg-white rounded-2xl shadow-sm p-4 mb-4">
              <Text className="text-base font-bold text-gray-900 block mb-2">游客信息</Text>
              <Text className="text-xs text-gray-500 block mb-4">请填写每张票的游客信息</Text>
              <View className="space-y-4">
                {ticketInfos.map((ticket, index) => (
                  <View key={index} className="border border-gray-200 rounded-lg p-3">
                    <View className="flex items-center justify-between mb-3">
                      <Text className="text-sm font-medium text-blue-600">{getTicketTypeName(index)}</Text>
                      {contacts.length > 0 && (
                        <Button
                          size="mini"
                          className="bg-green-50 text-green-600 rounded-lg text-xs px-2"
                          style={{backgroundColor: '#f0fdf4', color: '#16a34a'}}
                          onClick={() => openContactSelectorForVisitor(index)}>
                          <View className="flex items-center gap-1">
                            <View className="i-mdi-account-plus text-xs"></View>
                            <Text className="text-green-600">选择</Text>
                          </View>
                        </Button>
                      )}
                    </View>
                    <View className="space-y-3">
                      <View>
                        <Text className="text-xs text-gray-600 block mb-1">姓名</Text>
                        <Input
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
                          placeholder="请输入游客姓名"
                          value={ticket.visitor_name}
                          onInput={(e) => updateTicketInfo(index, 'visitor_name', e.detail.value)}
                        />
                      </View>
                      <View>
                        <Text className="text-xs text-gray-600 block mb-1">手机号</Text>
                        <Input
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
                          placeholder="请输入游客手机号"
                          type="number"
                          maxlength={11}
                          value={ticket.visitor_phone}
                          onInput={(e) => updateTicketInfo(index, 'visitor_phone', e.detail.value)}
                        />
                      </View>
                      <View>
                        <Text className="text-xs text-gray-600 block mb-1">身份证号</Text>
                        <Input
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
                          placeholder="请输入游客身份证号"
                          maxlength={18}
                          value={ticket.visitor_id_card}
                          onInput={(e) => updateTicketInfo(index, 'visitor_id_card', e.detail.value.toUpperCase())}
                        />
                      </View>
                    </View>
                  </View>
                ))}
              </View>
            </View>
          )}
        </View>
      </ScrollView>

      {/* 底部提交栏 */}
      {selections.size > 0 && (
        <View className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4 safe-area-inset-bottom">
          <View className="flex items-center justify-between mb-3">
            <View>
              <Text className="text-xs text-gray-500 block">共 {getTotalTickets()} 张票</Text>
              <Text className="text-xl font-bold text-blue-600 block mt-1">¥{Number(getTotalAmount()).toFixed(2)}</Text>
            </View>
            <Button
              size="default"
              className="px-8 py-3 bg-blue-600 text-white rounded-full font-medium text-base break-keep"
              onClick={handleSubmit}
              disabled={submitting}>
              {submitting ? '提交中...' : '提交订单'}
            </Button>
          </View>
        </View>
      )}

      {/* 联系人选择对话框 */}
      {showContactSelector && (
        <View
          className="fixed inset-0 flex items-center justify-center z-50"
          style={{backgroundColor: 'rgba(0,0,0,0.5)'}}>
          <View className="bg-white rounded-2xl p-6 mx-4 w-full max-w-md max-h-96 overflow-y-auto">
            <View className="flex items-center justify-between mb-4">
              <View>
                <Text className="text-xl font-bold text-gray-900">选择联系人</Text>
                {selectingForVisitor !== null && (
                  <Text className="text-xs text-gray-500 mt-1">为 {getTicketTypeName(selectingForVisitor)} 选择</Text>
                )}
              </View>
              <View
                className="i-mdi-close text-2xl text-gray-400"
                onClick={() => {
                  setShowContactSelector(false)
                  setSelectingForVisitor(null)
                }}></View>
            </View>

            <View className="space-y-3">
              {contacts.map((contact) => (
                <View
                  key={contact.id}
                  className="p-4 bg-gray-50 rounded-xl"
                  onClick={() => handleSelectContact(contact)}>
                  <View className="flex items-center justify-between mb-2">
                    <Text className="text-base font-bold text-gray-900">{contact.name}</Text>
                    {contact.is_default && (
                      <View className="px-2 py-0.5 bg-blue-100 rounded">
                        <Text className="text-xs text-blue-600 font-medium">默认</Text>
                      </View>
                    )}
                  </View>
                  <Text className="text-sm text-gray-600 block">手机号：{contact.phone}</Text>
                  <Text className="text-sm text-gray-600 block mt-1">
                    身份证：{contact.id_card.replace(/^(.{6})(?:\d+)(.{4})$/, '$1********$2')}
                  </Text>
                </View>
              ))}
            </View>

            <View className="mt-4">
              <Button
                size="default"
                className="w-full bg-blue-600 text-white py-3 rounded-lg font-bold text-base mt-6"
                style={{backgroundColor: '#2563eb', color: '#ffffff'}}
                onClick={() => {
                  setShowContactSelector(false)
                  Taro.navigateTo({url: '/pages/contacts/index'})
                }}>
                <View className="flex items-center justify-center gap-2">
                  <View className="i-mdi-plus text-lg"></View>
                  <Text className="text-white">添加新联系人</Text>
                </View>
              </Button>
            </View>
          </View>
        </View>
      )}
    </View>
  )
}

export default Booking
